package com.itheima.mall.api.sms;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mall.exception.BusinessException;
import com.itheima.mall.mapper.pms.ProductMapper;
import com.itheima.mall.mapper.sms.HomeBrandMapper;
import com.itheima.mall.pojo.pms.Product;
import com.itheima.mall.pojo.sms.SmsHomeBrand;
import com.itheima.mall.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class HomeBrandServiceApiImpl implements HomeBrandServiceApi{
@Autowired
    HomeBrandMapper brandMapper;
@Autowired
    ProductMapper productMapper;

    @Override
    public void createBrand(SmsHomeBrand homeBrand) {
        brandMapper.insert(homeBrand);
    }

    @Override
    public boolean deleteBrand(int[] ids) {
        Boolean flag=true;
        for (int id : ids) {
            LambdaQueryWrapper<Product> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Product::getBrandId,id);
            List<Product> products = productMapper.selectList(wrapper);
            if(products.size()==0){
            brandMapper.deleteById(Convert.toLong(id));}
            else {
               flag=false;
            }
        }
        return flag;
    }

    @Override
    public PageResult<SmsHomeBrand> getList(String brandName, Integer pageNum, Integer pageSize, Integer recommendStatus) {
        Page<SmsHomeBrand> pageInfo=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmsHomeBrand> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(brandName!=null,SmsHomeBrand::getBrandName,brandName);
        queryWrapper.eq(recommendStatus!=null,SmsHomeBrand::getRecommendStatus,recommendStatus);
        Page<SmsHomeBrand> page = brandMapper.selectPage(pageInfo, queryWrapper);
        PageResult<SmsHomeBrand> pageResult=new PageResult<>();
        pageResult.setList(page.getRecords());
        pageResult.setTotalPage(Convert.toInt(page.getCurrent()));
        pageResult.setPageSize(Convert.toInt(page.getSize()));
        pageResult.setPageNum(Convert.toInt(page.getPages()));
        pageResult.setTotalPage(Convert.toInt(page.getSize()));
        return pageResult;
    }

    @Override
    public void updateStatus(Integer recommendStatus, int[] ids) {
        for (int id : ids) {
            SmsHomeBrand smsHomeBrand=new SmsHomeBrand();
            smsHomeBrand.setId(Convert.toLong(id));
            smsHomeBrand.setRecommendStatus(recommendStatus);
            brandMapper.updateById(smsHomeBrand);
        }
    }

    @Override
    public void updateSort(Integer id, Integer sort) {
        SmsHomeBrand smsHomeBrand=new SmsHomeBrand();
        smsHomeBrand.setId(Convert.toLong(id));
        smsHomeBrand.setSort(sort);
        brandMapper.updateById(smsHomeBrand);
    }
}
